#include "ecgwavewidget.h"
#include <PXUtils.h>
#include <QPainter>
#include <QWidget>

EcgWaveWidget::EcgWaveWidget(QWidget *parent)
    : QWidget(parent),m_drawPos(0),m_midY(0)
{
    //该窗口部件不会接收任何鼠标事件（点击、移动、释放等）
    // 鼠标事件会穿透这个部件，传递给下面的部件
    //部件本身仍然可见，只是对鼠标"不可见"
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_NoSystemBackground);
    setAutoFillBackground(false);
    //设置透明背景
    //setStyleSheet("background: transparent;");
    auto CmToPx =  PXUtils::calcCmToPx(); //1cm = px
    CmToPxValue = CmToPx.first; // 水平像素密度
    qDebug() << "EcgWaveWidget::初始化";
    pen = QPen(Qt::blue);
    pen.setWidth(1);                // 细线宽度
    pen.setStyle(Qt::SolidLine);    // 实线，不是虚线或点线
    pen.setCapStyle(Qt::FlatCap);   // 线端平直
    pen.setJoinStyle(Qt::MiterJoin);// 拐角平滑
    pen.setCosmetic(true); //无论缩放与否，线宽都保持为1像素
}
EcgWaveWidget::~EcgWaveWidget()
{

}

void EcgWaveWidget::addDataPoint(const QList<int> &data)
{
    //qDebug() << "EcgWaveWidget::addDataPoint data size:" << data.size();
    draw(data);
}

void EcgWaveWidget::setGain(double gain)
{
    m_gain = gain;
    qDebug() << "EcgWaveWidget::setGain:" << m_gain;
}

void EcgWaveWidget::setSpeed(double speed)
{
    m_speed = speed;
    qDebug() << "EcgWaveWidget::setSpeed:" << speed;
    calculateStep();

}
//计算宽度 mm/s
void EcgWaveWidget::calculateStep(){
    //1s的点占的像素点
    double speedPx = m_speed * 0.1 * CmToPxValue;
    //再除采样率，一个点间隔多少像素
    step = speedPx / 150; //假设采样率150Hz
    OneScreenPointCount = int( canvasWidth / step );

    qDebug() << "EcgWaveWidget::calculateStep step:" << step << "OneScreenPointCount:" << OneScreenPointCount;
}

void EcgWaveWidget::resizeEvent(QResizeEvent *)
{
    qDebug() << "EcgWaveWidget::resizeEvent";
    // 重新创建缓冲画布
    image = QImage(size(), QImage::Format_ARGB32_Premultiplied);
    image.fill(Qt::transparent);
    m_midY = height() / 2;
    m_drawPos = 0;
    m_pixmap_reset = true;
    canvasWidth = width();
    calculateStep();
}
void EcgWaveWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing,true); //打开抗锯齿
    painter.drawImage(0, 0, image);
}
void EcgWaveWidget::draw(const QList<int> &_data)
{
    if (image.isNull() || _data.isEmpty())
        return;
    QImage tempImage = image; // 复制当前图像
    QPainter p(&tempImage);
    p.setRenderHint(QPainter::Antialiasing,true); //打开抗锯齿);

    // 擦除当前区域（留一点余量）
    double eraseWidth = _data.size() * step;
    QRect eraseRect(m_drawPos, 0, eraseWidth + 5, height() );

    p.save();
    p.setCompositionMode(QPainter::CompositionMode_Source);//CompositionMode_Clear);
    p.fillRect(eraseRect, Qt::transparent);
    p.restore(); // 恢复状态

    // 绘制新波形
    p.setPen(pen);
    p.setBrush(Qt::NoBrush);
    p.setCompositionMode(QPainter::CompositionMode_Source );
    double x = m_drawPos;
    for (int i = 0,len = _data.size(); i < len; i++ )
    {
        int value = _data[i];
        //归一化[-1,1]   这里要根据实际心电图的AD采样精度和放大倍数来计算，这里只是一个简单的例子 归一化+放大因子来调整基础波形，再乘以增益
        double normalize = (value - 127.5) / 127.5;
        double factor = 10.0;
        double y = m_midY -  normalize * factor * m_gain * CmToPxValue * 0.1 ;
        double yLast = 0;
        double xLast = 0;
        if(-9999 == m_lastValue){ //不存在上一点【首次】
            yLast = y;
            xLast = x;
        }else{ //存在上一点
            yLast = m_midY - m_lastValue * factor * m_gain * CmToPxValue * 0.1 ;
            xLast = x - step;
        }
        p.drawLine(xLast, yLast, x, y);
        m_lastValue = normalize;
        qDebug() << i << ",canvasWidth:"  << canvasWidth << "step:" << step << ",xLast:" << xLast << "yLast:" << yLast << "x:" << x << "y:" << y;
        x  = x + step;
        if( x > canvasWidth ) {
           x = 0;
        }
    }
    //更新绘制位置
    m_drawPos = x;
    image = tempImage;
    update();
}
